﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.Collections;
using KOF.Views;
using KOF.Helpers;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using Microsoft.Xna.Framework.Media;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Data;
using System.Collections.ObjectModel;
using Microsoft.Phone.Net.NetworkInformation;
using System.Windows.Navigation;
using System.Windows.Threading;

namespace ListBoxVisualStatesDemo
{
    public partial class MainPage : PhoneApplicationPage
    {

        private ScrollViewer sv = null;
        private bool _isBouncy = false;
        private bool alreadyHookedScrollEvents = false;
        int loaders = 0;
        // Constructor
        public MainPage()
        {


            try
            {
                //This Code checks internet Connection
                if (NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
                {

                }
                else
                {
                    MessageBox.Show("Please check your internet connection!");
                }

                //Initialize UI
                InitializeComponent();
                GoogleAnalytics.EasyTracker.GetTracker().SendView("Release tabs");
                //This Code gets Selected Brands Stored in local Application

                if (IsolatedStorageSettings.ApplicationSettings.Contains("SelectedBrands"))
                {
                    ObservableCollection<ResponseBrand> lstTempBrands = new ObservableCollection<ResponseBrand>();
                    ObservableCollection<ResponseBrand> lstSavedBrands = (ObservableCollection<ResponseBrand>)IsolatedStorageSettings.ApplicationSettings["SelectedBrands"];

                    if (lstSavedBrands != null)
                    {
                        foreach (ResponseBrand brand in lstSavedBrands)
                        {
                            KOF.Helpers.ResponseBrand newRec = new KOF.Helpers.ResponseBrand();
                            newRec.id = brand.id;
                            newRec.brand_name = brand.brand_name;
                            newRec.subtypes = brand.subtypes;
                            if (brand.subtypes != null && brand.subtypes.Count > 0)
                            {
                                foreach (ResponseBrand sub in brand.subtypes)
                                {
                                    if (sub.checked1) lstTempBrands.Add(sub);
                                }
                            }
                            lstTempBrands.Add(newRec);
                        }
                    }
                    (KOF.App.Current as KOF.App).gSelectedBrands = lstTempBrands;
                }


                // Selects Status Upcoming or past from local Applocation Storage
                if (IsolatedStorageSettings.ApplicationSettings.Contains("ReleaseStatus"))
                {
                    (KOF.App.Current as KOF.App).ReleaseStatus = (int)IsolatedStorageSettings.ApplicationSettings["ReleaseStatus"];
                    (KOF.App.Current as KOF.App).ReleaseStatusTemp = (int)IsolatedStorageSettings.ApplicationSettings["ReleaseStatus"];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            // Set the data context of the listbox control to the sample data
            DataContext = KOF.App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);



        }



        System.Windows.Threading.DispatcherTimer myDispatchTimer = new System.Windows.Threading.DispatcherTimer();

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {

                //Load Data of first Page =1;
                if (!KOF.App.ViewModel.IsDataLoaded)
                {

                    load.Visibility = System.Windows.Visibility.Visible;
                    KOF.App.ViewModel.LoadData();

                }


                if (alreadyHookedScrollEvents)
                {
                    load.Visibility = System.Windows.Visibility.Collapsed;
                    return;
                }

                alreadyHookedScrollEvents = true;
                MainListBox.AddHandler(ListBox.ManipulationCompletedEvent, (EventHandler<ManipulationCompletedEventArgs>)LB_ManipulationCompleted, true);

                //This Code finds ScrollBar when we scroll
                sv = (ScrollViewer)FindElementRecursive(MainListBox, typeof(ScrollViewer));


                // This Code will Find State of ScrollBar  | Vartical CompressionBottom | NotScrolling | NoVerticalCompression
                if (sv != null)
                {
                    // Visual States are always on the first child of the control template 
                    FrameworkElement element = VisualTreeHelper.GetChild(sv, 0) as FrameworkElement;
                    if (element != null)
                    {
                        VisualStateGroup vgroup = FindVisualState(element, "VerticalCompression");
                        if (vgroup != null)
                        {
                            vgroup.CurrentStateChanging += new EventHandler<VisualStateChangedEventArgs>(vgroup_CurrentStateChanging);
                        }
                    }
                }

                if (IsolatedStorageSettings.ApplicationSettings.Contains("loader"))
                {
                    load.Visibility = System.Windows.Visibility.Collapsed;

                    if (Convert.ToBoolean(IsolatedStorageSettings.ApplicationSettings["loader"]) == true)
                    {
                        load.Visibility = System.Windows.Visibility.Visible;
                    }
                }

                myDispatchTimer.Interval = System.TimeSpan.FromSeconds(5);
                myDispatchTimer.Tick += new EventHandler(newTimer_Tick);

                myDispatchTimer.Start();


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

        }

        private void LB_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            try
            {

                if (_isBouncy)
                {
                    ReleaseBounce();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

        }

        void newTimer_Tick(object sender, EventArgs e)
        {

            if (loaders == 0)
            {
                load.Visibility = System.Windows.Visibility.Collapsed;

                loaders = 1;
            }
            else
            {
                myDispatchTimer.Stop();

            }
        }

        //Process Code Based on Vertical States Changed.
        private void vgroup_CurrentStateChanging(object sender, VisualStateChangedEventArgs e)
        {

            try
            {
                if (e.NewState.Name == "CompressionBottom")
                {
                    ProcessBounce();

                    load.Visibility = System.Windows.Visibility.Visible;
                    KOF.App.ViewModel.getReleaseList();
                }
                if (e.NewState.Name == "NotScrolling")
                {
                    load.Visibility = System.Windows.Visibility.Collapsed;

                }
                if (e.NewState.Name == "NoVerticalCompression")
                {
                    ReleaseBounce();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        private void ReleaseBounce()
        {
            try
            {
                _isBouncy = false;
                load.Visibility = System.Windows.Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        private void ProcessBounce()
        {
            try
            {
                load.Visibility = System.Windows.Visibility.Visible;
                _isBouncy = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        //when it will find scrollviewer then will scroll and bind items.
        private UIElement FindElementRecursive(FrameworkElement parent, Type targetType)
        {

            int childCount = VisualTreeHelper.GetChildrenCount(parent);
            UIElement returnElement = null;
            if (childCount > 0)
            {
                for (int i = 0; i < childCount; i++)
                {
                    Object element = VisualTreeHelper.GetChild(parent, i);
                    if (element.GetType() == targetType)
                    {
                        return element as UIElement;
                    }
                    else
                    {
                        returnElement = FindElementRecursive(VisualTreeHelper.GetChild(parent, i) as FrameworkElement, targetType);
                    }
                }
            }
            // load.Visibility = System.Windows.Visibility.Collapsed;
            return returnElement;
        }

        // Find States
        private VisualStateGroup FindVisualState(FrameworkElement element, string name)
        {
            if (element == null)
                return null;

            IList groups = VisualStateManager.GetVisualStateGroups(element);
            foreach (VisualStateGroup group in groups)
                if (group.Name == name)
                {

                    return group;
                }

            return null;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {

            base.OnNavigatedFrom(e);
        }


        //Redirect To Refine Screen
        private void btnRefine_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.NavigationService.Navigate(new Uri("/Views/Refine.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        //Redirect To Favorite Screen
        private void btnFavorites_Click(object sender, EventArgs e)
        {
            try
            {

                this.NavigationService.Navigate(new Uri("/Views/Favorites.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        //Redirect To Setting Screen
        private void btnSettings_Click(object sender, EventArgs e)
        {
            try
            {
                this.NavigationService.Navigate(new Uri("/Views/Settings.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        //Redirect To News Page
        private void btnNews_Click(object sender, EventArgs e)
        {
            try
            {
                this.NavigationService.Navigate(new Uri("/Views/News.xaml", UriKind.Relative));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }


        // Onlist Click Redirect to ShoeDetails screen
        private void List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {

                if (MainListBox.SelectedIndex == -1)
                    return;

                KOF.Helpers.ReleaseResult item = e.AddedItems[0] as KOF.Helpers.ReleaseResult;

                (KOF.App.Current as KOF.App).lstImages = item.iphone_images;

                this.NavigationService.Navigate(new Uri(String.Format("/Views/ShoeDetails.xaml?id={0}&title={1}&style={2}&source={3}&type={4}&desc={5}&eventdate={6}&images={7}", item.id, item.title, item.style, item.kof_link, item.type, item.description, item.event_date, item.iphone_images), UriKind.Relative));

                MainListBox.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }


        }
    }
}